<?php

namespace App\Services\Manger;

use App\Models\Manger\Manger;
use App\Models\Manger\Mangerrule;
use App\Models\Manger\Menulist;
use App\Models\Manger\MenulistNnew;
use Illuminate\Support\Facades\Redis;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class MangerAccount
{

    public static function checkAccount(string $username, int $mid = 0)
    {
        //所有管理员以及子账号参与判断

        //新增账号判断是否重复

        //编辑账号判断是否重复


    }





    public static  function setMangerRule($manger_id,$utype){
        $select_arr = ['id', 'pid', 'name', 'path', 'props','hidden', 'component', 'always_show', 'title', 'icon',  'is_botton',
             DB::raw('(if(FIND_IN_SET('.$utype.',rule_typestr),1,0)) as is_checked')
            ];
            $menulist = MenulistNnew::where(['pid' => 0])->WhereRaw('FIND_IN_SET(?,max_rule_typestr)', [$utype])
                ->select($select_arr)->get();


            foreach ($menulist as &$val) {
                $buttonList = MenulistNnew::where(['pid' => $val->id, 'is_botton' => 1])->WhereRaw('FIND_IN_SET(?,max_rule_typestr)', [$utype])->select($select_arr)->get();
                $val->meta = ['title' => $val->title, 'icon' => $val->icon,'buttonList'=>$buttonList];
                unset($val->title);
                unset($val->icon);
                $submenu = MenulistNnew::where(['pid' => $val->id, 'is_botton' => 0])->WhereRaw('FIND_IN_SET(?,max_rule_typestr)', [$utype])->select($select_arr)->get();
                $val->props=$val->props?json_decode($val->props,true):[];
                foreach ($submenu as &$vval) {
                    $vval_buttonList = MenulistNnew::where(['pid' => $vval->id, 'is_botton' => 1])->WhereRaw('FIND_IN_SET(?,max_rule_typestr)', [$utype])->select($select_arr)->get();
                    $vval->meta = ['title' => $vval->title, 'icon' => $vval->icon,'buttonList'=>$vval_buttonList];
                    $vval->props=$vval->props?json_decode($vval->props,true):[];

                    unset($vval->title);
                    unset($vval->icon);


                    $subsubmenu = MenulistNnew::where(['pid' => $vval->id, 'is_botton' => 0])->WhereRaw('FIND_IN_SET(?,max_rule_typestr)', [$utype])->select($select_arr)->get();

                    foreach ($subsubmenu as &$vvval) {
                        $vvval_buttonList = MenulistNnew::where(['pid' => $vvval->id, 'is_botton' => 1])->WhereRaw('FIND_IN_SET(?,max_rule_typestr)', [$utype])->select($select_arr)->get();

                        $vvval->meta = ['title' => $vvval->title, 'icon' => $vvval->icon,'buttonList'=>$vvval_buttonList];
                        $vvval->props=$vvval->props?json_decode($vvval->props,true):[];

                        unset($vvval->title);
                        unset($vvval->icon);

                    }
                    $vval->children =$subsubmenu;
                }
                $val->children = $submenu;
            }


            Redis::set('manger_user_menulist_' . $manger_id.'_'.$utype, json_encode($menulist));


            Mangerrule::updateOrCreate(['mid' => $manger_id,'utype'=>$utype],['ruleinfo' => json_encode($menulist)]);


    }

    public static  function setMangerRulenewold(int $manger_id, int $utype)
    {

        $select_arr = ['id', 'pid', 'name', 'path', 'props','hidden', 'component', 'always_show', 'title', 'icon', 'no_cache', 'link', 'is_botton',
        'menu_ower', 'is_default as is_checked'];
        $menulist = Menulist::where(['menu_ower' => $utype, 'pid' => 0])
            ->select($select_arr)->get();


        foreach ($menulist as &$val) {
            $val->meta = ['title' => $val->title, 'icon' => $val->icon];
            unset($val->title);
            unset($val->icon);
            $submenu = Menulist::where(['menu_ower' => $utype, 'pid' => $val->id, 'is_botton' => 0])->select($select_arr)->get();
            $buttonlist = Menulist::where(['menu_ower' => $utype, 'pid' => $val->id, 'is_botton' => 1])->select($select_arr)->get();
            $val->props=$val->props?json_decode($val->props,true):[];
            foreach ($submenu as &$vval) {
                $vval->meta = ['title' => $vval->title, 'icon' => $vval->icon];
                $vval->props=$vval->props?json_decode($vval->props,true):[];

                unset($vval->title);
                unset($vval->icon);
                $vval->buttonlist = Menulist::where(['menu_ower' => $utype, 'pid' => $vval->id, 'is_botton' => 1])->select($select_arr)->get();
                $subsubmenu = Menulist::where(['menu_ower' => $utype, 'pid' => $vval->id, 'is_botton' => 0])->select($select_arr)->get();
                foreach ($subsubmenu as &$vvval) {
                    $vvval->meta = ['title' => $vvval->title, 'icon' => $vvval->icon];
                    $vvval->props=$vvval->props?json_decode($vvval->props,true):[];

                    unset($vvval->title);
                    unset($vvval->icon);
                    $vvval->buttonlist = Menulist::where(['menu_ower' => $utype, 'pid' => $vvval->id, 'is_botton' => 1])->select($select_arr)->get();
                }
                $vval->children =$subsubmenu;
            }
            $val->children = $submenu;
            $val->buttonlist = $buttonlist;
        }
        //设置人员权限redis缓存

        Redis::set('manger_user_menulist_' . $manger_id.'_'.$utype, json_encode($menulist));

        // Mangerrule::create(['mid' => $manger_id,'utype'=>$utype, 'ruleinfo' => json_encode($menulist)]);


        Mangerrule::updateOrCreate(['mid' => $manger_id,'utype'=>$utype],['ruleinfo' => json_encode($menulist)]);

        // Mangerrule::where(['mid' => $manger_id])->update(['ruleinfo' => json_encode($menulist)]);
    }

    public static function setMangerRuleold(int $manger_id, int $utype)
    {

        $select_arr=['id','pid','name','path','hidden','component','always_show','title','icon','no_cache','link','is_botton','menu_ower','is_default as is_checked'];
        $menulist = Menulist::where(['menu_ower' => $utype, 'pid' => 0])
        ->select($select_arr)->get();


        foreach ($menulist as &$val) {
            $val->meta=['title'=>$val->title,'icon'=>$val->icon];
            unset($val->title);
            unset($val->icon);
            $submenu = Menulist::where(['menu_ower' => $utype, 'pid' => $val->id, 'is_botton' => 0])->select($select_arr)->get();
            $buttonlist = Menulist::where(['menu_ower' => $utype, 'pid' => $val->id, 'is_botton' => 1])->select($select_arr)->get();

            foreach ($submenu as &$vval) {
                $vval->meta=['title'=>$vval->title,'icon'=>$vval->icon];
                unset($vval->title);
                unset($vval->icon);
                $vval->buttonlist = Menulist::where(['menu_ower' => $utype, 'pid' => $vval->id, 'is_botton' => 1])->select($select_arr)->get();
            }
            $val->children = $submenu;
            $val->buttonlist = $buttonlist;
        }
        //设置人员权限redis缓存

        Redis::set('manger_user_menulist_' . $manger_id, json_encode($menulist));


        Mangerrule::create(['mid' => $manger_id, 'ruleinfo' => json_encode($menulist)]);
    }

    /**
     * 设置用户权限缓存
     */
    public static function serMangerRuleCache(int $manger_id, int $utype)
    {

        $rule_info = Mangerrule::where(['mid' => $manger_id])->first();
        if (!$rule_info) {
            return;
        }

        //根据前端需求存储对应格式

        $ruleinfo = json_decode($rule_info->ruleinfo);
        foreach ($ruleinfo as $val) {
            //剔除无用资料

        }
    }


    /**
     * 存储登陆状态
     */
    public static function storeTokenKey($token, $adminid)
    {
        Redis::set('manger_user_tokenbyid_' . $adminid, $token);
    }

    /**
     * 删除登录状态
     */

    public static function clearTokenKey($manger_id)
    {

        Redis::delete('manger_user_tokenbyid_' . $manger_id);
    }

    /**
     * 获取各端的账号列表
     */
    public static function getMangerList(Request $request, $cpid, $utype, $status, $isgetall)
    {
        $query = Manger::
        // with(['department','cpduserinfo'])
        with(['department'])
        ->where(['cpid' => $cpid])->where('utypes','<>','1')->orderBy('create_at', 'desc');
        if (in_array($status, [1, 2])) {
            $query->where('status', $status);
        }
        $realname = $request->realname;

        if ($realname != '') {
            $query->where('realname', 'like', '%' . $realname . '%');
        }

        $code_no = $request->code_no;
        if ($code_no != '') {
            $query->where('code_no', 'like', '%' . $code_no . '%');
        }
        /***
         *  当前数据表 utype字段 全部为1，管理员。每个管理员有多种角色，可视化分析获取 业务员、采购员时，按现在数据，只搜索
         *  utypes 字段包含 6，7 就认为是 业务员（7） 采购员（6）
         *
         */
        $filter_utype = $request->filter_utype;
        if($filter_utype == ''){
            if (in_array($utype, [2, 3, 4, 5, 6, 7, 8])) {
                $query->WhereRaw('FIND_IN_SET(?,utypes)', [$utype]);
            }
        }else{
            if (in_array($filter_utype, [2, 3, 4, 5, 6, 7, 8])) {
                $query->WhereRaw('FIND_IN_SET(?,utypes)', [$filter_utype]);
            }
        }
//        if($filter_utype != ''){
//            $query->where('utype', $utype);
//        }

        if ($isgetall == 0) {
            $limit = $request->limit ?? 10;
            $list = $query->select(['id', 'utypes', 'code_no', 'username', 'mobile', 'realname', 'status','cpd_user_id','sys_dpm_id'])->paginate($limit)->toArray();
            return paginateDataToArray($list);
        } else {
            $list = $query->select(['id', 'utypes', 'code_no', 'username', 'mobile', 'realname', 'status','cpd_user_id','sys_dpm_id'])->get()->toArray();

            return ['list' => $list];
        }
    }


    /**
     * 获取用户列表
     */
    public static function getAccountList(Request $request, $cpid, $sys_dpm_id,$utype, $isgetall)
    {
        $query = Manger::where(['cpid' => $cpid])
            ->where('utypes','<>','1')
            ->where('status','=','1')
            ->where('sys_dpm_id','=',$sys_dpm_id)
            ->orderBy('create_at', 'desc');

//        $realname = $request->realname;
//        if ($realname != '') {
//            $query->where('realname', 'like', '%' . $realname . '%');
//        }
//
//        $code_no = $request->code_no;
//        if ($code_no != '') {
//            $query->where('code_no', 'like', '%' . $code_no . '%');
//        }

        if (in_array($utype, [2, 3, 4, 5, 6, 7, 8])) {
            $query->WhereRaw('FIND_IN_SET(?,utypes)', [$utype]);
        }
        if ($isgetall == 0) {
            $limit = $request->limit ?? 10;
            $list = $query->select(['id','code_no','realname'])->paginate($limit)->toArray();
            return paginateDataToArray($list);
        } else {
            $list = $query->select(['id','code_no','realname'])->get()->toArray();

            return ['list' => $list];
        }
    }

    /**
     * 配置用户账号
     */

    public function setMangerAccount()
    {
    }
}
